var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var fs = require('fs'); //文件模块
var twig = require("twig");

var app = express();


app.set('view engine', 'twig');
// This section is optional and used to configure twig.
app.set("twig options", {
    cache: false,
    auto_reload: true,
});
app.set('view cache', false);

// view engine setup
app.set('views', path.join(__dirname, 'views'));


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.get('*', function (request, res) {
    let pp = request.path.substr(1, request.path.length - 1)
    if (pp == '' || pp == null) {
        pp = 'index';
    }
    res.render(pp, load_data(pp));
});

function load_twig(file) {

    let ff = './views/' + file + '.twig'
    console.log('path:', file);
    if (fs.existsSync(ff)) {
        let a27 = fs.readFileSync(ff, {
            encoding: 'utf8'
        });
        console.log('data:', a27);
        return a27;
    }
    return '';
}


function load_data(file) {
    let ff = './data/' + file + '.json';
    console.log('path:', file);
    if (fs.existsSync(ff)) {
        let a27 = fs.readFileSync(ff, {
            encoding: 'utf8'
        });
        console.log('data:', a27);
        return JSON.parse(a27);
    }
    return {};
}

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
